package com.bdc.HBase;

import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hdfs.web.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.bdc.HBase.HBaseClientApi.*;
import static com.bdc.HBase.HBaseUtils.getConnection;

public class HBaseDemo {
    private static final Logger logger = LoggerFactory.getLogger(HBaseDemo.class);

    public static void main(String[] args) {

        Connection connection = null;
        try {
            connection = getConnection();
            TableName tableName = TableName.valueOf("DeviceState");

            //创建DeviceState表
            createTable(connection, tableName, "name", "state");

            logger.info("创建表 {}", tableName.getNameAsString());

            //写入数据
            put(connection, tableName, "row1", "name", "c1", "空调");
            put(connection, tableName, "row1", "state", "c2", "打开");
            put(connection, tableName, "row2", "name", "c1", "电视机");
            put(connection, tableName, "row2", "state", "c2", "关闭");

            logger.info("写入数据.");

            String value = getCell(connection, tableName, "row1", "state", "c2");
            logger.info("读取单元格-row1.state:{}", value);

            Map<String, String> row = getRow(connection, tableName, "row2");
            //logger.info("读取单元格-row2:{}", JsonUtil.toJson(row));

            List<Map<String, String>> dataList = scan(connection, tableName, null, null);
            //logger.info("扫描表结果-:\n{}", JsonUtil.toPrettyJson(dataList));

            //删除DeviceState表
            deleteTable(connection, tableName);
            logger.info("删除表 {}", tableName.getNameAsString());

            logger.info("操作完成.");
        } catch (Exception e) {
            logger.error("操作出错", e);
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    logger.error("error occurs", e);
                }
            }
        }

    }
}
